/**
 * The MIT License (MIT)
 * 
 * Copyright (c) 2016 mo_yq5 (mo_yq5@163.com)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 */
package com.vulgarsdk.captcha;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 验证码发送和验证的默认实现类，一般的手机号和邮箱验可以直接使用本对象实例完成需要的功能， 当然也可以自定义覆盖相应的方法来满足自己的需要。
 * 
 * @author mo_yq5
 * @since 2016年1月10日
 */
public class CaptchaVerifierDefault extends CaptchaVerifierAbstract {
	private static Logger log = LoggerFactory
			.getLogger(CaptchaVerifierDefault.class);

	@Override
	public boolean check(String account, String captcha) {

		Captcha cap = (Captcha) session.get(sessionKey);

		// 没输入验证码、验证码信息不存在、验证账号不一致、或者验证码信息已过期
		if (null == captcha
				|| null == cap
				|| !account.equals(cap.getAccount())
				|| (new Date().getTime() - cap.getTimestamp()) > setting
						.getIndate() * 60000) {
			return false;
		}

		// 输入不正确，并累计错误次数
		if (!captcha.equals(cap.getCaptcha())) {
			cap.setFailTimes(cap.getFailTimes() + 1);
			session.set(sessionKey, cap);
			return false;
		}

		// 已达到允许错误次数
		if (cap.getFailTimes() >= setting.getBreak()) {
			return false;
		}

		// 正确后再删,使不能重复使用
		session.remove(sessionKey);
		return true;
	}

	@Override
	public void send(String account) throws CaptchaException {
		Captcha cap = (Captcha) session.get(sessionKey);

		// 操作过于频繁
		if (null != cap
				&& cap.getTimestamp() + setting.getLag() * 1000 > new Date()
						.getTime()) {
			throw new CaptchaLagException();
		}

		String captcha = null;
		switch (setting.getType()) {
		case DIGIT:
			captcha = CaptchaUtils.mkDigitCaptcha(setting.getLength());
			break;
		case LETTER:
			captcha = CaptchaUtils.mkLetterCaptcha(setting.getLength());
			break;
		case MIXTURE:
			captcha = CaptchaUtils.mkMixtureCaptcha(setting.getLength());
			break;
		}

		log.debug("发送验证码：account={}, captcha={}", account, captcha);

		// session
		cap = new Captcha();
		cap.setCaptcha(captcha);
		cap.setAccount(account);
		session.set(sessionKey, cap);

		// 发短信
		sender.send(account, captcha, setting.getIndate());

	}

}
